// pages/player/player.js
let musiclist = []
let nowPlayingIndex = 0
// 获取全局背景音频管理器 唯一
const backgroundAudioManager = wx.getBackgroundAudioManager()
// 调用全局app.js里面的方法
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    picUrl:'',
    isPlaying: false,
    // 当前歌词是否显示
    isLyricShow: false,
    // 歌词内容
    lyric: '',
    // 是否为同一首歌
    isSame: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    const musicId = options.musicid
    nowPlayingIndex = options.index
    musiclist = wx.getStorageSync('musiclist')
    this._loadMusicDetail(musicId)
  },

  _loadMusicDetail(musicId) {
    // 判断是否为同一首歌
    if (musicId == app.getPlayMusicId()) {
      this.setData({
        isSame: true
      })
    } else {
      this.setData({
        isSame: false
      })
    }
    if (!this.data.isSame) {
      backgroundAudioManager.stop()
    }
    let music = musiclist[nowPlayingIndex]
    console.log(musicId)
    wx.setNavigationBarTitle({
      title: music.name,
    })
  this.setData({
    picUrl: music.al.picUrl,
    isPlaying: false
  })
    // 解决音乐切换时音乐名称高亮显示
    app.setPlayMusicId(musicId)

    wx.showLoading({
      title: '歌曲加载中',
    })
  wx.cloud.callFunction({
      name: 'music',
      data: {
        musicId,
        $url: 'musicUrl',
      }
    }).then((res) => {
      // console.log(res)
      // console.log(JSON.parse(res.result))
      let result = JSON.parse(res.result)
      if (result.data[0].url == null) {
        wx.showToast({
          title: '无权限播放',
        })
        return
      }
      if(!this.data.isSame) {
        backgroundAudioManager.src = result.data[0].url
        backgroundAudioManager.title = music.name
        backgroundAudioManager.coverImgUrl = music.al.picUrl
        backgroundAudioManager.singer = music.ar[0].name
        backgroundAudioManager.epname = music.al.name
        // 保存播放历史
        this.savePlayHistory()
      }
      this.setData({
        isPlaying: true
      })
      wx.hideLoading()
      // 加载歌词
      wx.cloud.callFunction({
        name: 'music',
        data: {
          musicId,
          $url: 'lyric',
        }
      }).then((res) => {
        // console.log(res)
        let lyric = '暂无歌词'
        // JSON.parse转化为对象
        const lrc = JSON.parse(res.result).lrc
        if(lrc) {
          lyric = lrc.lyric          
        }
        this.setData({
          lyric
        })
      })
  })
  },
  togglePlaying() {
    if(this.data.isPlaying) {
      backgroundAudioManager.pause()
    } else {
      backgroundAudioManager.play()
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  onPrev() {
    nowPlayingIndex--
    if (nowPlayingIndex < 0) {
      // nowPlayingIndex为倒数第一首歌曲
      nowPlayingIndex = musiclist.length - 1
    }
    this._loadMusicDetail(musiclist[nowPlayingIndex].id)
  },
  onNext() {
    nowPlayingIndex++
    if (nowPlayingIndex === musiclist.length) {
      // nowPlayingIndex为第一首歌曲
      nowPlayingIndex = 0
    }
    this._loadMusicDetail(musiclist[nowPlayingIndex].id)
  },
  onChangeLyricShow() {
    this.setData({
      isLyricShow: !this.data.isLyricShow
    })
  },
  timeUpdate(e) {
    // 把时间传递给歌词组件 根据类名选取组件 定义方法传递参数
    this.selectComponent('.lyric').update(e.detail.currentTime)
  },
  onPlay() {
    this.setData({
      isPlaying: true
    })
  },
  onPause() {
    this.setData({
      isPlaying: false
    })
  },
  // 保存播放历史
  savePlayHistory() {
    // 获取当前播放的歌曲
    const music = musiclist[nowPlayingIndex]
    const openid = app.globalData.openid
    const history = wx.getStorageSync(openid)
    let bHave = false
    for (let i = 0, len = history.length; i < len; i++) {
      if(history[i].id == music.id) {
        bHave = true
        break
      }
    }
    if (!bHave) {
      // unshift向数组开头插入元素并返回长度
      history.unshift(music)
      wx.setStorage({
        key: openid,
        data: history
      })
    }
  }
})